package com.example.homelicaisystem.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.web.context.request.RequestContextHolder;

import java.util.Calendar;

import static org.springframework.web.context.request.RequestAttributes.SCOPE_REQUEST;

public class UserUtil {
    private static final String SIGNATURE = "1234";
    private static final int TOKEN_TIME = 20000;
    private static final String ID = "id";

    /**
     * 生成token header.payload.sign
     */
    public static String getToken(int userId) {
        // 创建jwt builder
        JWTCreator.Builder builder = JWT.create();
        // payload
        builder.withClaim(ID, userId);
        // token过期时间
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.SECOND, TOKEN_TIME);
        builder.withExpiresAt(instance.getTime());
        // toekn签名
        return builder.sign(Algorithm.HMAC256(SIGNATURE));
    }

    /**
     * 从token当中获取用户ID的方法
     */
    public static int getUserIdByToken(String token) {
        DecodedJWT jwt = JWT.require(Algorithm.HMAC256(SIGNATURE)).build().verify(token);
        return jwt.getClaim(ID).asInt();
    }

    /**
     * 将用户信息保存下来
     *
     * @param id
     */
    public static void saveUser(Integer id) {
        RequestContextHolder.getRequestAttributes().setAttribute(ID, id, SCOPE_REQUEST);
    }

    /**
     * 在bean里面获取用户ID的方法
     */
    public static Integer getUserId() {
        return (Integer) RequestContextHolder.getRequestAttributes().getAttribute(ID, SCOPE_REQUEST);
    }
}
